package com.sike.netty.im.server.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.sike.netty.im.common.command.AbstractResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.common.enums.Attributes;
import com.sike.netty.im.common.enums.ResponseStatusEnum;
import com.sike.netty.im.server.util.LoginUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;


/**
 * 服务端统一异常处理 handler
 *
 * @author chenssy
 * @date 2023/09/17
 */
@Slf4j
public class
ServerExceptionHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("Exception :{}", ExceptionUtil.stacktraceToString(cause));

        Class clase = (Class) ctx.attr(AttributeKey.valueOf(Attributes.SERVER_EXCEPTION_RESPONSE_CLASS.getKey())).get();
        AbstractResponseCommand commandBody = (AbstractResponseCommand) clase.newInstance();
        commandBody.setRetCode(ResponseStatusEnum.FAILURE.getCode());
        commandBody.setRetMessage(cause.getMessage());

        Message message = MessageBuilder.buildMessage(commandBody,null, LoginUtil.getLoginUser(ctx.channel()));
        ctx.channel().writeAndFlush(message);
    }
}
